package cn.yunhe.action;

import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.ServletActionContext;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

/**
 * Created by Administrator on 2017/6/30.
 */
public class UpAction extends ActionSupport {
    //文件
    private File[] upload;
    //文件类型
    private String[] uploadContentType;
    //文件名
    private String[] uploadFileName;
    //保存路径
    private String savePath;


    public String execute() throws Exception {
        //文件=完整路径+文件名
        for (int i = 0; i < upload.length; i++) {
            String uploadPath = getSavePath() + "\\" + uploadFileName[i];
            doUpload(upload[i], uploadPath);
        }
        return SUCCESS;
    }

    /**
     * 上传操作
     *
     * @param file
     * @param uploadFilePath
     */
    private void doUpload(File file, String uploadFilePath) {
        //输入流和输出流
        try {
            FileOutputStream fos = new FileOutputStream(uploadFilePath);
            FileInputStream fis = new FileInputStream(file);

            byte[] buffer = new byte[1024];
            int len = 0;

            //边读边写
            while ((len = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }

            fis.close();
            fos.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public File[] getUpload() {
        return upload;
    }

    public void setUpload(File[] upload) {
        this.upload = upload;
    }

    public String[] getUploadContentType() {
        return uploadContentType;
    }

    public void setUploadContentType(String[] uploadContentType) {
        this.uploadContentType = uploadContentType;
    }

    public String[] getUploadFileName() {
        return uploadFileName;
    }

    public void setUploadFileName(String[] uploadFileName) {
        this.uploadFileName = uploadFileName;
    }

    public String getSavePath() {
        return ServletActionContext.getServletContext().getRealPath(savePath);
    }

    public void setSavePath(String savePath) {
        this.savePath = savePath;
    }
}
